/* 导出列表 */
<template>
  <a-modal
    :title="title"
    :width="1600"
    :height="1000"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    :bodyStyle="bodyStyle"
    @cancel="handleCancel"
    cancelText="关闭"
    wrapClassName="ant-modal-cust-warp"
    style="top:8%;height: 70%;overflow-y: hidden"
  >
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <!-- 搜索区域 -->
      <a-form layout="inline" @keyup.enter.native="searchQuerys">
        <a-row :gutter="24">
          <a-col :md="6" :sm="24">
            <a-form-item label="所属行业" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入所属行业查询" v-model="queryParam.industry"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="客户名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input placeholder="请输入客户名称查询" v-model="queryParam.customerName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="业务负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select
                :disabled="disable"
                v-model="queryParam.businessLeader"
                allowClear
                placeholder="请输入业务负责人查询"
                showSearch
                optionFilterProp="children"
              >
                <a-select-option v-for="(item, index) in personList" :key="index" :value="item">
                  {{ item }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="24">
            <a-form-item label="签约时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-range-picker
                style="width: 100%"
                :placeholder="['开始时间', '结束时间']"
                v-model="queryParam.createTime"
                @change="onDateChange"
                format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
            <a-col :md="6" :sm="24">
              <a-button type="primary" @click="searchQuerys">查询</a-button>
              <a-button style="margin-left: 8px" @click="searchResets">重置</a-button>
            </a-col>
          </span>
        </a-row>
      </a-form>
    </div>
    <template slot="footer">
      <a-button key="back" v-if="isReadOnly" @click="handleCancel">
        关闭
      </a-button>
      <a-button @click="handleClick" type="primary" icon="download">导出</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <div class="table-operator" style="margin-top: 5px"></div>
      <div>
        <a-table
          ref="table"
          size="middle"
          bordered
          rowKey="id"
          :columns="columns"
          :dataSource="dataSource"
          :pagination="false"
          :rowClassName="tableRowClass"
          :scroll="{ x: 1500, y: 600 }"
          :loading="loading"
          @change="handleTableChange"
        >
          <span slot="action" slot-scope="text, record">
            <a @click="myhandkeEdit(record)">编辑</a>
            <a-divider type="vertical" />
            <a-popconfirm title="确定删除吗?" @confirm="() => myhandleDelete(record.id)">
              <a>删除</a>
            </a-popconfirm>
          </span>
          <!-- 状态渲染模板 -->
          <template slot="customRenderFlag" slot-scope="enabled">
            <a-tag v-if="enabled" color="green">启用</a-tag>
            <a-tag v-if="!enabled" color="orange">禁用</a-tag>
          </template>
        </a-table>
      </div>
    </a-spin>
    <AddInstall ref="modalForm" @ok="reModalFormOk"></AddInstall>
  </a-modal>
</template>
<script>
import { export_table_to_excel } from '@/mixins/vendor/Exoprt2Excel-Custom-Anywo'
import pick from 'lodash.pick'
import { addCustomer, checkSupplier, personList } from '@/api/api'
import { getAction, deleteAction } from '@/api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import AddInstall from './AddInstall'
import { autoJumpNextInput } from '@/utils/util'
export default {
  name: 'AlertExport',
  mixins: [JeecgListMixin],
  components: {
    AddInstall
  },
  data() {
    return {
      title: '导出列表',
      visible: false,
      disable: false,
      personList: [],
      model: {},
      isReadOnly: true,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      bodyStyle: {
        padding: '20',
        height: window.innerHeight * 0.7 + 'px',
        'overflow-y': 'auto'
      },
      confirmLoading: false,
      isDownload: false,
      form: this.$form.createForm(this),
      // 表头
      columns: [
        {
          title: '所属行业',
          dataIndex: 'industry',
          width: 80,
          align: 'center',
          customRender: (text, record, index) => {
            const obj = {
              children: text,
              attrs: {}
            }
            if (text.includes('小计')) {
              obj.attrs.colSpan = 4
            }
            return obj
          }
        },
        {
          title: '客户名称',
          dataIndex: 'customerName',
          width: 100,
          align: 'center',
          customRender: (text, record, index) => {
            const obj = {
              children: text,
              attrs: {}
            }
            if (text.includes('小计')) {
              obj.attrs.colSpan = 3
            } else if (!text) {
              obj.attrs.colSpan = 0
            } else if (text.includes('总计')) {
              obj.attrs.colSpan = 3
            }
            return obj
          }
        },
        {
          title: '内部合同编码',
          dataIndex: 'contractCode',
          width: 80,
          align: 'center',
          customRender: (text, record, index) => {
            const obj = {
              children: text,
              attrs: {}
            }
            if (!text) {
              obj.attrs.colSpan = 0
            }
            return obj
          }
        },
        {
          title: '合同编号',
          dataIndex: 'contractNum',
          width: 60,
          align: 'center',
          customRender: (text, record, index) => {
            const obj = {
              children: text,
              attrs: {}
            }
            if (!text) {
              obj.attrs.colSpan = 0
            }
            return obj
          }
        },
        {
          title: '业务负责人',
          dataIndex: 'businessLeader',
          width: 70,
          align: 'center'
        },
        {
          title: '合同总金额',
          dataIndex: 'contractAmount',
          width: 70,
          align: 'center'
        },
        {
          title: '已收金额',
          dataIndex: 'receivedAmount',
          width: 70,
          align: 'center'
        },
        {
          title: '未收金额',
          dataIndex: 'uncollectedAmount',
          width: 70,
          align: 'center'
        },
        {
          title: '开票金额',
          dataIndex: 'invoicedAmount',
          width: 70,
          align: 'center'
        },
        {
          title: '签约时间',
          dataIndex: 'signedDate',
          width: 60,
          align: 'center'
        },
        {
          title: '发货时间',
          dataIndex: 'deliveryDate',
          width: 60,
          align: 'center'
        }
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   width: 100,
        //   align: 'center',
        //   fixed: 'right',
        //   scopedSlots: { customRender: 'action' }
        // }
      ],
      url: {
        lists: '/contractdetails/exportExcel',
        delete: '/contractProductDelivery/remove'
      }
    }
  },
  created() {},
  methods: {
    defaultSelect() {
      personList().then(res => {
        if (res.code == 200 || res.code == 10000) {
          this.personList = res.data
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // filterData() {
    //   let a = JSON.parse(sessionStorage.getItem('UserMessage'))
    //   let useMsg = JSON.parse(sessionStorage.getItem('User'))
    //   if (a) {
    //     this.queryParam.businessLeader = useMsg.ename
    //     params.businessLeader = useMsg.ename
    //     this.disable = true
    //   } else {
    //     this.disable = false
    //   }
    // },
    //导出excel
    handleClick() {
      this.isDownload = true
      var time = this.$moment().format('MM/DD')
      let fileName = '合同明细导出' + time + '.xlsx'
      this.$nextTick(() => {
        export_table_to_excel({ ref: this.$refs.table, fileName })
        this.isDownload = false
      })
    },
    myhandleDelete: function(id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      console.log(id)
      var that = this
      deleteAction(that.url.delete, { id: id }).then(res => {
        if (res.code === 200 || res.code === 10000) {
          that.reModalFormOk()
        } else {
          that.$message.warning(res.data.message)
        }
      })
    },
    tableRowClass(record) {
      if (record.customerName.includes('小计')) {
        return 'rowClass'
      } else if (record.customerName.includes('总计')) {
        return 'totalClass'
      } else if (record.industry.includes('小计')) {
        return 'rowClass1'
      } else {
        return ''
      }
    },
    searchResets() {
      this.getActionList()
    },
    //保存成功后刷新列表
    reModalFormOk() {
      this.getActionList(this.model)
    },
    // myhandkeEdit(record) {
    //   this.$refs.modalForm.edit(record)
    //   this.$refs.modalForm.title = '编辑'
    //   this.$refs.modalForm.disableSubmit = false
    // },
    searchQuerys() {
      var params = this.getQueryParams() //查询条件
      console.log(params, 'params')
      this.getActionList(params)
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.defaultSelect()
      this.getActionList(record)
    },
    //请求列表数据
    getActionList(record) {
      this.dataSource = []
      this.loading = true
      let params = {}
      console.log(record, 'record')
      if (record) {
        record.industry ? (params.industry = record.industry) : ''
        record.startDate ? (params.startDate = record.startDate) : ''
        record.endDate ? (params.endDate = record.endDate) : ''
        record.customerName ? (params.customerName = record.customerName) : ''
        record.businessLeader ? (params.businessLeader = record.businessLeader) : ''
      } else {
        // //判断全部还是个人数据
        // this.filterData()
        let a = JSON.parse(sessionStorage.getItem('UserMessage'))
        let useMsg = JSON.parse(sessionStorage.getItem('User'))
        if (a) {
          this.queryParam.businessLeader = useMsg.ename
          params.businessLeader = useMsg.ename
          this.disable = true
        } else {
          this.disable = false
        }
      }
      //页码字段未统一
      params.current = this.ipagination.current
      params.currentPage = this.ipagination.current
      params.size = this.ipagination.pageSize
      params.pageSize = this.ipagination.pageSize
      getAction(this.url.lists, params).then(res => {
        if (res.code === 200 || res.code === 10000) {
          res.data.industryTotalExportVoList.map(item => {
            const c = {
              industry: '',
              customerName: '',
              customerContractExportVoList: [
                {
                  industry: item.industryName + '行业小计',
                  contractAmount: item.industryAmountExportVo.amountTotal,
                  contractCode: '',
                  contractNum: '',
                  customerName: '',
                  deliveryDate: '',
                  invoicedAmount: item.industryAmountExportVo.invoicedTotal,
                  receivedAmount: item.industryAmountExportVo.receivedTotal,
                  uncollectedAmount: item.industryAmountExportVo.receivableTotal
                }
              ]
            }
            item.customerTotalExportVoList.push(c)
            console.log(item, 'xxxxxxxxxx')
            item.customerTotalExportVoList.map(itemChildren => {
              if (itemChildren.customerAmountExportVo) {
                const a = {
                  industry: itemChildren.industry,
                  contractAmount: itemChildren.customerAmountExportVo.amountTotal,
                  contractCode: '',
                  contractNum: '',
                  customerName: itemChildren.customerName + '--客户小计',
                  deliveryDate: '',
                  invoicedAmount: itemChildren.customerAmountExportVo.invoicedTotal,
                  receivedAmount: itemChildren.customerAmountExportVo.receivedTotal,
                  uncollectedAmount: itemChildren.customerAmountExportVo.receivableTotal
                }
                itemChildren.customerContractExportVoList.push(a)
              }

              // console.log(itemChildren,'xxxxxxxxxx')
              itemChildren.customerContractExportVoList.map(e => {
                this.dataSource.push(e)
              })
            })
          })
          const b = {
            industry: '',
            contractAmount: res.data.contractAmountExportVo.amountTotal,
            contractCode: '',
            contractNum: '',
            customerName: '总计',
            deliveryDate: '',
            invoicedAmount: res.data.contractAmountExportVo.invoicedTotal,
            receivedAmount: res.data.contractAmountExportVo.receivedTotal,
            uncollectedAmount: res.data.contractAmountExportVo.receivableTotal
          }
          this.dataSource.push(b)
        }
      })
      this.loading = false
    },
    close() {
      this.$emit('close')
      this.queryParam = {}
      this.visible = false
    },
    onDateChange: function(value, dateString) {
      this.queryParam.startDate = dateString[0]
      this.queryParam.endDate = dateString[1]
      console.log(this.queryParam)
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values)
          if (this.model.beginNeedGet && this.model.beginNeedPay) {
            that.$message.warn('期初应收和期初应付不能同时输入')
            that.confirmLoading = false
            return
          }
          let obj
          if (!this.model.id) {
            obj = addCustomer(formData)
          } else {
            obj = addCustomer(formData)
          }
          obj
            .then(res => {
              if (res.code === 200 || res.code === 10000) {
                this.$message.success('保存成功')
                that.$emit('ok')
              } else {
                that.$message.warning(res.data.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
              that.close()
            })
        }
      })
    },
    handleCancel() {
      this.close()
    },
    validateSupplierName(rule, value, callback) {
      let params = {
        name: value,
        type: '客户',
        id: this.model.id ? this.model.id : 0
      }
      checkSupplier(params).then(res => {
        if (res && res.code === 200) {
          if (!res.data.status) {
            callback()
          } else {
            callback('名称已经存在')
          }
        } else {
          callback(res.data)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
@import '~@assets/less/common.less';
/deep/ .rowClass {
  background-color: rgb(147, 230, 232);
  font-weight: 800;
}
/deep/ .rowClass1 {
  background-color: rgb(201, 225, 248);
  font-weight: 800;
}
/deep/ .totalClass {
  background-color: rgb(245, 197, 6);
  font-weight: 800;
}
</style>
